<#include "/common/content_layout.html"/>
<@layout>
<style type="text/css">
 #table tr{
 	vertical-align:top;
 }
 #table td{
 	padding:8px;
 }
 #url{
 	width:400px;
 }
 #btnExc{
 	padding:4px;
 	/* background-color:#339e35; */
 	margin-right:8px;
 }
 #btnSave{
 	padding:4px;
 	/* background-color:#339e35; */
 	margin-right:8px;
 }
</style>
<script type="text/javascript">
var Tool = function(){
     //  var type_data = [{ type: "string", text: '字符串' }, { type: "int", text: '数字'}, { type: "floatt", text: '布尔值'}];
     this.dataType = {"string":"字符串", "number":"数字(整数/浮点数)", "boolean":"布尔值", "object":"对象"};
     this.getDataTypeStr = function(data){
         var type = "string";
         switch(typeof(data)){
         	case "number":
         		type = "number";
             	break;
         	case "string":
         		type = "string";
             	break;
         	case "boolean":
         		type = "boolean";
             	break;
         	case "object":
         		type = "object";
         		break;
             default:
             	type = "string";
         }
         return type;
     }
     this.getDataTypeArray = function(){
         var arr = [];
         for(var k in dataType){
             var d = {};
             d['type'] = k;
             d['text'] = dataType[k];
         	arr.push(d);
         }
         return arr;
     }
     return this;
 }();

function addNewRow(){
    var manager = $.request_maingrid;
    manager.addRow({
    	"id":manager.rows.length + 1,
    	"en_name" : "",
    	//"cn_name": "",
        "type": "string",
        "default_value":"",
    });
}

function saveItem(){
	var rows = $.request_maingrid.rows;
	if(rows.length > 0){
		var obj = {};
		for(var i = 0; i < rows.length; i++){
			var d = {};
			var r = rows[i];
			obj[r['en_name']] = r['default_value'];
			if(r['type'] == "object"){
				obj[r['en_name']] = jQuery.parseJSON(r['default_value']);
			}
		}
		$('#request').val(JSON.stringify(obj))
	}
}


function deleteRow(item){
	var manager = null;
	if(item.id == "assertDelete"){
		manager = $.assert_maingrid;
	}
	else{
		manager = $.request_maingrid;
	}
    var rows_select = manager.getSelectedRows();
    
    if(rows_select.length > 0){
    	
    	$.ligerDialog.confirm('提示内容', function (yes) {
    		if(yes == true){
    			
        		var datas= {};
            	for(var i = 0; i < rows_select.length; i++){
            		var r = rows_select[i];
            		datas[r.id] = true;
                }
                manager.deleteSelectedRow();
                var rows2 = manager.rows;
                var i = 1;
                for(var key in rows2){
                	var r = rows2[key];
                	if(!!datas[r.id] != true){
                		var selected = manager.getRow(r.__id);
                		manager.updateRow(selected,{
                	    	id: i
                	    });
                		i++;
                	}
                }
    		}
    		
		});

    }
    else{
    	$.ligerDialog.warn('请先选择参数');
    }
}


function addAssert(){
	var rows = $.response_maingrid.getSelectedRows();
	if(rows.length > 0){
		var assertRows = $.assert_maingrid.rows;
		var assertValue = {};
		var delArr = [];
		for(var i = 0; i < assertRows.length; i++){
			var r = assertRows[i];
			var en_name = r['en_name'];
			if(en_name != ""){
				assertValue[en_name] = true;
			}
			else{
				$.assert_maingrid.deleteRow(r.__id);
			}
		}
		var isExist = true;
		for(var i = 0; i < rows.length; i++){
			var r = rows[i];
			var d = {};
			//d['cn_name'] = r['cn_name'];
			d['default_value'] = r['default_value'];
			d['en_name'] = r['en_name'];
			d['type'] = r['type'];
			d['assert_type'] = 'not';
			if(!!assertValue[d['en_name']] == false){
				$.assert_maingrid.addRow(d);
				isExist = false;
			}
		}
		if(isExist == true){
			$.ligerDialog.success('字段重复，请选择其它字段判断');
		}
	}
	else{
		$.ligerDialog.success('请先选择字段');
	}
	//$.assert_maingrid.update();
}

function getAssertValue(){
	var rows = $.assert_maingrid.rows;
	var datas = [];
	if(rows.length > 0){
		for(var i = 0; i < rows.length; i++){
			var r = rows[i];
			var d = {};
			d['assert_type'] = r['assert_type'];
			d['default_value'] = r['default_value'];
			d['en_name'] = r['en_name'];
			d['type'] = r['type'];
			datas[i] = d;
		}
		var id = $("#id").val();
	}
	return JSON.stringify(datas);
}

function saveAssert(item){
	var id = $("#id").val();
	var assert_value = getAssertValue();
	$.post("/api/saveAssert", {"id":id, "assert_value":assert_value},
	   function(data){
	  		if(data.state == 'success'){
	  			$.ligerDialog.success('保存成功');
	  		}
	  		else{
	  			$.ligerDialog.error('保存失败');
	  		}
	   }, "json");
}

$(function (){
	var type_data = Tool.getDataTypeArray();//[{ type: "string", text: '字符串' }, { type: "int", text: '数字'}, { type: "floatt", text: '布尔值'}];

	// 请求参数解析
	var CustomersData = {Rows:[
                               {"en_name":"reqseq1","cn_name":"","type":"字符串", "default_value":"2014"},
                               {"en_name":"reqseq2","cn_name":"","type":"字符串", "default_value":"2014"},
                               {"en_name":"reqseq3","cn_name":"","type":"字符串", "default_value":"2014"}
                               ]};
    $.request_maingrid = $("#request_maingrid").ligerGrid({
    	checkbox: true,
    	columns: [
				  { display: '序号', name: 'id', align: 'middle', width: 50},
                  { display: '英文名', name: 'en_name', align: 'left', width: 100, editor: { type: 'text' }},
                  //{ display: '中文名', name: 'cn_name',width: 50, editor: { type: 'text' }},
                  { display: '类型', name: 'type', width: 100, editor: { type: 'select', data: type_data, valueField: 'type' },
                	  render: function (item){
		            	    for(var i = 0; i < type_data.length; i++){
			            	    if(type_data[i].type == item.type){
				            	    return type_data[i].text;
			            	    }
		            	    }
	                    }},
                  { display: '默认值', name: 'default_value',width: 300,editor: { type: 'text' }}
                  ],
        width: 600, 
        height: 200,
        data: CustomersData,
        //rownumbers: true,
        enabledEdit: true,
        usePager:false,
        isScroll:true,
        toolbar: { items: [
						   { text: '删除', click: deleteRow, icon: 'modify' },
                           { line: true },
                           { text: '添加', click: addNewRow, icon: 'add' },
                           { line: true },
                           { text: '保存到参数', click: saveItem, icon: 'save' }
                           
                    ]
                  }
        
    }
    );

 // 响应结果解析
    var TreeDeptData = {Rows:[
                              // {"en_name":"","cn_name":"","":"字符串", "default_value":""}
                              ]
    };
    $.response_maingrid = $("#response_maingrid").ligerGrid({
    	columns: [
                  { display: '英文名', name: 'en_name', align: 'left', width: '25%'},
                  //{ display: '中文名', name: 'cn_name',width: '25%'},
                  { display: '类型', name: 'type', width: '25%',editor: { type: 'select', data: type_data, valueField: 'type' },
                	  render: function (item){
		            	    for(var i = 0; i < type_data.length; i++){
			            	    if(type_data[i].type == item.type){
				            	    return type_data[i].text;
			            	    }
		            	    }
	                    }
                      },
                  { display: '返回值判断', name: 'default_assert',width: '25%',editor: { type: 'text' }},
                  { display: '默认值', name: 'default_value',width: '25%',editor: { type: 'text' }}
                  ],
        width: 600, 
        height: 200,
        data: TreeDeptData,
        //rownumbers: true,
        enabledEdit: true,
        usePager:false,
        isScroll:true,
        tree: { columnName: 'en_name' },
    	toolbar: { items: [
                       { text: '添加判断', click: addAssert, icon: 'add' }
                ]
              }
    }
    );

	var assert_data = [{type:"not",text:"不判断"},
	                   {type:"eq",text:"等于=="},
	                   {type:"ne",text:"不等于!="},
	                   {type:"gt",text:"大于>"},
	                   {type:"gte",text:"大于或等于>="},
	                   {type:"lt",text:"小于<"},
	                   {type:"lte",text:"小于或等于<="}
	                   ];
	
    // 响应内容判断
   //var assertData = {Rows:${useCase.get("assertValue")?default('[{"en_name":"","type":"","assert_type":"","default_value":""}]')}};
   var assertData = {Rows:${useCase.get("assertValue")?default("[]")}};
    $.assert_maingrid = $("#assert_maingrid").ligerGrid({
    	checkbox: true,
    	//resizable:false,
    	columns: [
                  { display: '英文名', name: 'en_name', align: 'left', width: 200},
                  { display: '类型', name: 'type', width: 100,editor: { type: 'select', data: type_data, valueField: 'type' },
                	  render: function (item){
		            	    for(var i = 0; i < type_data.length; i++){
			            	    if(type_data[i].type == item.type){
				            	    return type_data[i].text;
			            	    }
		            	    }
	                    }
                      },
                  { display: '返回值判断', name: 'assert_type', width: 100, editor: { type: 'select', data: assert_data, valueField: 'type' },
                      render: function (item){
  		            	    for(var i = 0; i < assert_data.length; i++){
  			            	    if(assert_data[i].type == item.assert_type){
  				            	    return assert_data[i].text;
  			            	    }
  		            	    }
  	                    }
                  },
                  { display: '默认值', name: 'default_value',width: 200,editor: { type: 'text' }}
                  ],
        width: 600, 
        height: 200,
        data: assertData,
        //rownumbers: true,
        enabledEdit: true,
        usePager:false,
        isScroll:true,
        tree: { columnName: 'en_name' },
        toolbar: { items: [
						   { text: '保存', click: saveAssert, icon: 'save' },
						   { line: true },
						   { text: '删除', click: deleteRow, icon: 'delete', id:'assertDelete'},
                    ]
                  }
    	}
    );
    
    
	$.navtab = $("#navtab").ligerTab({
		onAfterSelectTabItem: function (tabid){
	        switch(tabid){
	        	case 'tabitem1':
	        		request_maingrid_parse();
	            break;
	        	
	        }
	    }
	});
	
	$.navtab2 = $("#navtab2").ligerTab({
		onAfterSelectTabItem: function (tabid){
			//console.log("tabid:" + tabid);
	        switch(tabid){
	        	case 'tabitem1':
	        		response_maingrid_parse();
	            break;
	        	case 'tabitem2':
	        		assert_maingrid_parse();
	            break;
	        }
	    }
	});
});

function request_maingrid_parse(){
	var jsonStr = $("#request").val();
	if(jsonStr.length > 0){
		var len = $.request_maingrid.rows.length;
		for(var i = 0; i < len; i++){
			$.request_maingrid.deleteRow(0);
		}
		var json = jQuery.parseJSON(jsonStr);
		var i = 1;
		for(var key in json){//遍历json对象的每个key/value对,p为key
   			var typeStr = Tool.getDataTypeStr(json[key]);
   			var children = [];
   			var value = json[key];
   			if(typeStr == "object"){
   				value = JSON.stringify(json[key]);
   			}
   			var d = {
   				 id:i,
               	 en_name : key,
               	 cn_name: '',
               	 type: typeStr,
               	 default_value:value
                };
                $.request_maingrid.addRow(d);
                i++;
			}
	}
}

function response_maingrid_parse(){
	var jsonStr = $("#response").val();
	var type = $("#type").val();
	if(jsonStr.length > 0 && type != "text"){
		var len = $.response_maingrid.rows.length;

		for(var i = 0; i < len; i++){
			$.response_maingrid.deleteRow(0);
		}
		var json = jQuery.parseJSON(jsonStr);
		for(var key in json){//遍历json对象的每个key/value对,p为key
			var typeStr = Tool.getDataTypeStr(json[key]);
			var children = [];
			var value = json[key];
			if(Object.prototype.toString.call(json[key]) == '[object Object]'){
				for(var k in value){
					var tStr = Tool.getDataTypeStr(value[k]);
					var v = value[k];
					if(Object.prototype.toString.call(v) == '[object Array]'){
						v = JSON.stringify(v);
					}
    				var c = {
                          	 en_name : k,
                        	 cn_name: '',
                        	 type: tStr,
                        	 default_value:v
                         };
    				children.push(c);
				}
			}
			var v = json[key];
			if(Object.prototype.toString.call(v) == '[object Array]'){
				v = JSON.stringify(v);
			}
			var d = {
            	 en_name : key,
            	 cn_name: '',
            	 type: typeStr,
            	 default_value:v
             };
               if(children.length > 0){
                   d['children'] = children;
                   d['default_value'] = null;
               }
               $.response_maingrid.addRow(d);
             
			}
	}
}
// 值判断解析
function assert_maingrid_parse(){
	var jsonStr = $("#response").val();
	$.assert_maingrid.setWidth(200);

}

</script>

<div class="table_box">
<form action="">
<table id="table" cellpadding="20px">
<tr>
	<td>
		<div id="stateResult" style="padding: 8px; margin-top: 1em; background-color: #d4d4d4; color: white;">
			1/1 用例完成：<strong id="passCount">0</strong> 通过，<strong id="failCount">0</strong> 失败，<!-- ，<strong id="exceCount">0</strong> 异常 -->
			耗时：<strong id="time">0ms</strong>
		</div>
	</td>
</tr>
<tr>
	<input id="id" type="hidden" value="${id}"/>
	
	<td>请求地址:<input id="url" type="text" value="${(useCase.url)!}"/>&nbsp;<input id="btnExc" type="button" value="执行"/><input id="btnSave" type="button" value="保存"/></td>
</tr>
<tr>
	<td>
		请求方法:<select id="method">
					<option value="post" <#if (useCase.method!"")=="post">selected</#if> >POST</option>
					<option value="get" <#if (useCase.method!"")=="get">selected</#if> >GET</option>
				</select>
		内容类型:<select id="type">
					<option value="json" <#if (useCase.type!"")=="json">selected</#if> >application/json</option>
					<option value="text" <#if (useCase.type!"")=="text">selected</#if> >text/plain</option>
					
				</select>
		请求编码:<select id="code">
					<option value="UTF-8" <#if (useCase.code!"")=="UTF-8">selected</#if> >UTF-8</option>
					<option value="GBK" <#if (useCase.code!"")=="GBK">selected</#if> >GBK</option>
				</select>
		超时:<select id="timeOut">
					<option value="30" <#if (useCase.timeOut!"")==30 >selected</#if> >30s</option>
					<option value="60" <#if (useCase.timeOut!"")==60 >selected</#if> >1min</option>
					<option value="120" <#if (useCase.timeOut!"")==120 >selected</#if> >2min</option>
					<option value="300" <#if (useCase.timeOut!"")==300 >selected</#if> >5min</option>
				    <option value="600" <#if (useCase.timeOut!"")==600 >selected</#if> >10min</option>
				</select>
	</td>
</tr>

</table>

<div id="navtab"  style="width:600px;height: 30%;overflow:hidden; border:1px solid #A3C0E8;margin-top:6px; ">
	<!-- ==========请求报文start=========== -->
	<div tabid="home" title="请求参数" style="height:200px;" lselected="true"  >
		<textarea id="request" rows="7" cols="80" style="width:590px;">${(useCase.request)!}</textarea>&nbsp;&nbsp;
	</div>
	<!-- ==========请求报文end=========== -->
	<div  title="请求参数解析"  >
		<!-- <input type="button" value="保存" id="request_maingrid_save" class="l-button" >   -->
        <div id="request_maingrid"></div>
	</div>
	<!-- 
	<div  title="请求变量"  >
        <div id="request_maingrid2"></div>
	</div>
	 -->
</div>

<div id="navtab2"  style="width:600px;height: 30%;overflow:hidden; border:1px solid #A3C0E8;margin-top:6px; ">
	<div  tabid="home" title="响应内容" style="height:200px" lselected="true">
	    <textarea id="response" rows="7" cols="80" style="width: 590px;"></textarea>&nbsp;&nbsp;
	</div>
	<div  title="响应内容解析">
		<!-- 
	   <input type="button" value="保存" id="Button1" class="l-button" />	
	    -->
	   <div id="response_maingrid"></div>
	</div>
	<div  title="响应内容判断">
	   <div id="assert_maingrid"></div>
	</div>
	</div>
</form>

</div>
<script>


function parseGrid(grid, edit){
	var rows = grid.rows;
	if(rows.length > 0){
		var data = {};
		for(i = 0; i < rows.length; i++){
			var r = rows[i];
			var en_name = r['en_name'];
			var type = r['type'];
			var default_value = r['default_value'];
			data[en_name] = default_value;
		}
		edit.val(JSON.stringify(data))
	}
}
$("#btnSave").click(function(){
	if($.navtab.getSelectedTabItemID() == "tabitem1"){
		parseGrid($.request_maingrid, $("#request"));
	}
	//$('#stateResult').hide();
	$('#stateResult').css('background-color', '#d4d4d4');
	var id = $("#id").val();
	var url = $("#url").val();
	var method = $("#method").val();
	var type = $("#type").val();
	var code = $("#code").val();
	var request = $("#request").val();
	var assertValue = getAssertValue();
	var timeOut = $("#timeOut").val();
	$.post("/api/save", {"id":id, "url":url, "method": method, "type":type, "code":code,"request":request,"assertValue":assertValue,"timeOut":timeOut},
	   function(data){
	  		if(data.state == 'success'){
	  			$.ligerDialog.success('保存成功');
	  		}
	  		else{
	  			$.ligerDialog.error('保存失败');
	  		}
	   }, "json");
});
$("#btnExc").click(function(){
	if($.navtab.getSelectedTabItemID() == "tabitem1"){
		parseGrid($.request_maingrid, $("#request"));
	}
	$('#response').val('');
	$('#stateResult').css('background-color', '#d4d4d4');
	// $('#stateResult').hide();
	var id = $("#id").val();
	var url = $("#url").val();
	var method = $("#method").val();
	var type = $("#type").val();
	var code = $("#code").val();
	var request = $("#request").val();
	var assertValue = getAssertValue();
	var timeOut = $("#timeOut").val();
	$.post("/api/execute", {"id":id, "url":url, "method": method, "type":type, "code":code, "request":request, "assertValue":assertValue,"timeOut":timeOut},
			   function(data){
		   		if(data.state == 'success'){
		   			$('#response').val(JSON.stringify(data.data))
					$('#stateResult').show();
		   			$('#stateResult').css('background-color', 'green');
		   			$('#passCount').text(data.passCount);
		   			$('#failCount').text(data.failCount);
		   		}
		   		else{
		   			$('#stateResult').show();
		   			$('#stateResult').css('background-color', 'red');
		   		}
		   		$('#time').text(calTime(data.time));
		   		
			   }, "json");
});


</script>
</@layout>